package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Transactional
    public void saveWithFlavor(DishDto dto) {
        //保存菜的基本信息到菜品表
        this.save(dto);


        Long dishId = dto.getId();//菜品id
        //菜品口味
        List<DishFlavor> flavors = dto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //分两步先查询菜品的基本信息，再根据菜品id查询口味信息
        //先查询基本的菜品信息
        Dish dish = this.getById(id);
        //口味信息dish里没有，新增一个dishdto
        DishDto dishDto = new DishDto();
        //拷贝信息
        BeanUtils.copyProperties(dish,dishDto);
        //根据id从口味表查询
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        //Sql语句中where 前面是列表项后面是要查询的id，Sql语句 where DishFlavor::getDishId(口味表中的dishId) = (传来的菜品id)dish.getId
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        //调用查询方法，得到口味信息集合，下一步将口味设置进dishdto中
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //已经接收到修改后基本的菜品信息
        this.updateById(dishDto);
        //清理当前菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //添加当前提交过来的口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        //通过stream流的方式
        flavors = flavors.stream().map((item) ->{
            //设置菜品ID
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }



}
